package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.UUID;

/**
 * 入住Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-12-26
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper,CheckIn> implements ICheckInService
{

    private final CheckInMapper checkInMapper;
    private final IElderService elderService;
    private final IBedService bedService;
    private final ICheckInConfigService checkInConfigService;
    private final IContractService contractService;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkInDto 入住
     * @return 结果
     */
    @Override
    @Transactional
    public void apply(CheckInApplyDto checkInDto)
    {
        //搞清楚这个业务的本质，就是究竟要做什么，以及步骤
        //新增入住 存几张表而已！！
        //1.校验老人是否已经入住
        String idCardNo = checkInDto.getCheckInElderDto().getIdCardNo();
        Elder elder = elderService.getOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, idCardNo));
        //如果有老人信息且状态是入住中的，就不允许再次入住
        if(elder !=null && elder.getStatus() == Elder.STATUS_CHECKING){
            log.info("当前老人已经在入住中,身份证：{}",idCardNo);
            throw new BaseException("当前老人已经办理入住");
        }
        //2.更新床位状态
        Long bedId = checkInDto.getCheckInConfigDto().getBedId();
        Bed bed = bedService.selectBedById(bedId);
        if(bed == null){
            throw new BaseException("床位不存在");
        }
        bed.setBedStatus(Bed.STATUS_CHECKIN);
        bedService.updateById(bed);
        //3.新增到老人表中
        elder = saveElder(checkInDto, bed);
        //4.新增到入住表中
        CheckIn checkIn = saveCheckin(checkInDto, elder, bed);
        //5.新增到入住配置表中
        saveCheckConfig(checkInDto,checkIn);
        //6.新增到签约办理表中
        saveContract(checkInDto,elder);

    }

    /**
     * 保存合同信息
     * @param checkInDto
     * @param elder
     */
    private void saveContract(CheckInApplyDto checkInDto, Elder elder) {
        Contract contract = new Contract();
        CheckInContractDto checkInContractDto = checkInDto.getCheckInContractDto();
        BeanUtils.copyProperties(checkInContractDto,contract);
        //设置老人信息
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        //设置开始日期和结束日期
        CheckInConfigDto checkInConfigDto = checkInDto.getCheckInConfigDto();
        LocalDateTime startDate = checkInConfigDto.getStartDate();
        LocalDateTime endDate = checkInConfigDto.getEndDate();

        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        //合同状态处理，用当前日期和开始日期比较，如果开始日期大于= 当前日期，合同就生效，否则就未生效
        boolean after = startDate.isAfter(LocalDateTime.now());
        contract.setStatus(after ? Contract.STATUS_UNEFFECTIVE : Contract.STATUS_EFFECTIVE);
        //设置合同编号
        contract.setContractNumber(CodeGenerator.generateContractNumber());

        contractService.save(contract);
    }

    /**
     * 保存入住配置表
     * @param checkInDto
     * @param checkIn
     */
    private void saveCheckConfig(CheckInApplyDto checkInDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        //封装参数
        CheckInConfigDto checkInConfigDto = checkInDto.getCheckInConfigDto();
        BeanUtils.copyProperties(checkInConfigDto,checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());

        checkInConfigService.save(checkInConfig);
    }

    /**
     * 新增入住表
     * @param checkInDto
     */
    private CheckIn saveCheckin(CheckInApplyDto checkInDto,Elder elder,Bed bed) {
        CheckIn checkIn = new CheckIn();
        //封装数据
        CheckInConfigDto checkInConfigDto = checkInDto.getCheckInConfigDto();
        BeanUtils.copyProperties(checkInConfigDto,checkIn);
        //设置老人信息
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        //设置床位信息
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(CheckIn.STATUS_CHECK_IN);
        //保存家属信息
        checkIn.setRemark(JSONUtil.toJsonStr(checkInDto.getElderFamilyDtoList()));

        super.save(checkIn);
        return checkIn;
    }

    /**
     * 保存到老人表中
     * @param checkInDto
     */
    private Elder saveElder(CheckInApplyDto checkInDto,Bed bed) {
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInDto.getCheckInElderDto(),elder);
        //设置状态为入住中
        elder.setStatus(Elder.STATUS_CHECKING);
        //设置床位信息
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        elderService.saveOrUpdate(elder);
        return elder;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn)?1:0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id)?1:0;
    }

}
